package com.pace.ribbon.asyn.service.impl;

import com.pace.ribbon.asyn.service.HelloService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

@Service
public class HelloServiceImpl implements HelloService {


    @Override
    @Async
    public void iAsyncSay() throws InterruptedException {
        System.out.println("执行HelloServiceImpl.iAsyncSay开始，当前线程名称：" + Thread.currentThread().getName());
        Thread.sleep(2000);
        System.out.println("执行HelloServiceImpl.iAsyncSay结束");
    }

    @Override
    public String dealData(Object o) {
        List<String> list = (ArrayList) o;
        CountDownLatch countDownLatch = new CountDownLatch(list.size());
        ThreadPoolExecutor threadPool = createThreadPool();
        AtomicBoolean isSuccess = new AtomicBoolean(true);
        for (String item : list) {
            threadPool.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println("1asasasqqw121221,"+item);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                        isSuccess.set(false);
                    } finally {
                        countDownLatch.countDown();
                    }
                }
            });
        }
        try {
            countDownLatch.await(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            System.out.println("查询我的办理报价10s超时...");
        } finally {
            threadPool.shutdown();
        }
        System.out.println(!isSuccess.get());
        return null;
    }

    protected ThreadPoolExecutor createThreadPool() {
        return  new ThreadPoolExecutor(8, 20, 60000L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
    }
}
